from django.db import models
from django.core.validators import MinValueValidator
from django.utils import timezone


# 商品批次表
class FaKuyouGoodsBatch(models.Model):
    """商品批次表"""
    id = models.AutoField(primary_key=True, verbose_name='批次ID')
    admin_id = models.IntegerField(null=True, blank=True, verbose_name='管理员ID')
    goods_id = models.IntegerField(
        default=0,
        verbose_name='商品ID',
        help_text='关联的商品ID'
    )
    goods_code = models.CharField(
        max_length=30,
        null=True,
        blank=True,
        verbose_name='商品编号',
        help_text='商品的唯一编码'
    )
    attribute_id = models.IntegerField(
        default=0,
        null=True,
        blank=True,
        verbose_name='属性组合ID',
        help_text='商品属性组合ID'
    )
    stores_id = models.IntegerField(
        default=0,
        verbose_name='仓库ID',
        help_text='商品所在的仓库ID'
    )
    batch_name = models.CharField(
        max_length=255,
        null=True,
        blank=True,
        verbose_name='批次号',
        help_text='商品的批次号'
    )
    manufacture = models.PositiveIntegerField(
        null=True,
        blank=True,
        verbose_name='生产日期',
        help_text='Unix时间戳格式'
    )
    guarantee = models.PositiveIntegerField(
        null=True,
        blank=True,
        verbose_name='保质期',
        help_text='保质期天数'
    )
    validity = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='有效期至',
        help_text='Unix时间戳格式'
    )
    address = models.CharField(
        max_length=255,
        null=True,
        blank=True,
        verbose_name='产地',
        help_text='商品的生产地'
    )
    registration = models.CharField(
        max_length=255,
        null=True,
        blank=True,
        verbose_name='注册证号',
        help_text='商品的注册证号码'
    )
    production = models.CharField(
        max_length=255,
        null=True,
        blank=True,
        verbose_name='生产许可证',
        help_text='商品的生产许可证号'
    )
    createtime = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='创建时间',
        help_text='Unix时间戳格式'
    )
    updatetime = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='更新时间',
        help_text='Unix时间戳格式'
    )

    class Meta:
        db_table = 'fa_kuyou_goods_batch'
        verbose_name = '商品批次'
        verbose_name_plural = '商品批次'
        indexes = [
            models.Index(fields=['goods_id'], name='batch_goods_idx'),
            models.Index(fields=['stores_id'], name='batch_stores_idx'),
            models.Index(fields=['batch_name'], name='batch_name_idx'),
            models.Index(fields=['validity'], name='batch_validity_idx'),
        ]

    def __str__(self):
        return f"{self.batch_name or '无批次号'} (商品ID:{self.goods_id})"

    def save(self, *args, **kwargs):
        """自动处理时间戳和有效期"""
        # 自动设置时间戳
        if not self.createtime:
            self.createtime = int(timezone.now().timestamp())
        self.updatetime = int(timezone.now().timestamp())

        # 自动计算有效期
        if self.manufacture and self.guarantee:
            manufacture_date = timezone.datetime.fromtimestamp(self.manufacture)
            validity_date = manufacture_date + timezone.timedelta(days=self.guarantee)
            self.validity = int(validity_date.timestamp())

        super().save(*args, **kwargs)


# 商品退货批次详情表
class FaKuyouGoodsBatchExchangeInfo(models.Model):
    STATUS_CHOICES = (
        ('0', '关闭'),
        ('1', '正常'),
    )

    TYPE_CHOICES = (
        (0, '未知'),
        (1, '期初'),
        (2, '购货'),
    )

    id = models.AutoField(primary_key=True)
    admin_id = models.IntegerField(null=True, blank=True)
    batch_id = models.IntegerField(null=True, blank=True)
    goods_id = models.IntegerField(default=0)
    goods_code = models.CharField(max_length=30, null=True, blank=True)
    attribute_id = models.CharField(max_length=30, null=True, blank=True)
    goods_unit = models.IntegerField(null=True, blank=True)
    stores_id = models.IntegerField(default=0)
    stock = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000)
    status = models.CharField(max_length=1, choices=STATUS_CHOICES, default='1')
    number = models.FloatField(default=0.0000, null=True, blank=True)
    batch_name = models.CharField(max_length=255, null=True, blank=True)
    manufacture = models.PositiveIntegerField(null=True, blank=True)
    guarantee = models.PositiveIntegerField(null=True, blank=True)
    validity = models.IntegerField(null=True, blank=True)
    purchase_id = models.IntegerField(null=True, blank=True)
    purchase_info_id = models.IntegerField(null=True, blank=True)
    type = models.SmallIntegerField(choices=TYPE_CHOICES, default=0)
    createtime = models.IntegerField(null=True, blank=True)
    updatetime = models.IntegerField(null=True, blank=True)

    class Meta:
        db_table = 'fa_kuyou_goods_batch_exchange_info'
        verbose_name = '商品退货批次详情表'
        verbose_name_plural = verbose_name

    def __str__(self):
        return f"{self.batch_name} (ID: {self.id})"


# 商品销售批次详情表
class FaKuyouGoodsBatchSaleInfo(models.Model):
    """商品销售批次详情表"""
    STATUS_CHOICES = (
        ('0', '关闭'),
        ('1', '正常'),
    )
    TYPE_CHOICES = (
        (0, '普通'),
        (1, '期初'),
        (2, '购货'),
    )

    id = models.AutoField(primary_key=True, verbose_name='ID')
    admin_id = models.IntegerField(null=True, blank=True, verbose_name='管理员ID')
    batch_id = models.IntegerField(null=True, blank=True, verbose_name='关联批次ID')
    goods_id = models.IntegerField(
        default=0,
        verbose_name='商品ID',
        help_text='关联的商品ID'
    )
    goods_code = models.CharField(
        max_length=30,
        null=True,
        blank=True,
        verbose_name='商品编号',
        help_text='商品的唯一编码'
    )
    attribute_id = models.CharField(
        max_length=30,
        null=True,
        blank=True,
        verbose_name='属性组合ID',
        help_text='商品属性组合ID，多个属性用逗号分隔'
    )
    goods_unit = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='商品单位',
        help_text='商品的计量单位ID'
    )
    stores_id = models.IntegerField(
        default=0,
        verbose_name='仓库ID',
        help_text='商品所在的仓库ID'
    )
    stock = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        default=0.0000,
        validators=[MinValueValidator(0)],
        verbose_name='库存数量',
        help_text='当前库存数量'
    )
    status = models.CharField(
        max_length=1,
        choices=STATUS_CHOICES,
        default='1',
        verbose_name='状态',
        help_text='控制批次是否可用'
    )
    number = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        default=0.0000,
        null=True,
        blank=True,
        validators=[MinValueValidator(0)],
        verbose_name='期初数量',
        help_text='期初入库数量'
    )
    batch_name = models.CharField(
        max_length=255,
        null=True,
        blank=True,
        verbose_name='批次号',
        help_text='商品的批次号'
    )
    manufacture = models.PositiveIntegerField(
        null=True,
        blank=True,
        verbose_name='生产日期',
        help_text='Unix时间戳格式'
    )
    guarantee = models.PositiveIntegerField(
        null=True,
        blank=True,
        verbose_name='保质期',
        help_text='保质期天数'
    )
    validity = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='有效期至',
        help_text='Unix时间戳格式'
    )
    purchase_id = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='购货单号',
        help_text='关联的购货单ID'
    )
    purchase_info_id = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='购货单详情ID',
        help_text='关联的购货单详情ID'
    )
    type = models.SmallIntegerField(
        choices=TYPE_CHOICES,
        default=0,
        verbose_name='类型',
        help_text='批次来源类型'
    )
    createtime = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='创建时间',
        help_text='Unix时间戳格式'
    )
    updatetime = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='更新时间',
        help_text='Unix时间戳格式'
    )

    class Meta:
        db_table = 'fa_kuyou_goods_batch_sale_info'
        verbose_name = '商品销售批次详情'
        verbose_name_plural = '商品销售批次详情'
        indexes = [
            models.Index(fields=['batch_id'], name='batch_sale_batch_idx'),
            models.Index(fields=['goods_id'], name='batch_sale_goods_idx'),
            models.Index(fields=['stores_id'], name='batch_sale_stores_idx'),
            models.Index(fields=['validity'], name='batch_sale_validity_idx'),
            models.Index(fields=['purchase_id'], name='batch_sale_purchase_idx'),
            models.Index(fields=['type'], name='batch_sale_type_idx'),
        ]

    def __str__(self):
        return f"{self.batch_name or '无批次号'} (商品ID:{self.goods_id}, 库存:{self.stock})"

    def save(self, *args, **kwargs):
        """自动处理时间戳和有效期"""
        # 自动设置时间戳
        if not self.createtime:
            self.createtime = int(timezone.now().timestamp())
        self.updatetime = int(timezone.now().timestamp())


        super().save(*args, **kwargs)


# 批次跟踪表
class FaKuyouGoodsBatchLog(models.Model):
    BUSINESS_TYPE_CHOICES = (
        ('1', '期初余额'),
        ('2', '普通采购'),
        ('3', '采购退回'),
        ('4', '普通销售'),
        ('5', '销售退回'),
        ('6', '调拨单'),
        ('7', '盘盈'),
        ('8', '其他入库'),
        ('9', '盘亏'),
        ('10', '其他出库'),
        ('11', '组合单'),
        ('12', '组合单'),
        ('13', '拆卸单'),
        ('14', '拆卸单'),
        ('17', '生产单'),
        ('18', '领料单'),
        ('19', '退料单'),
        ('20', '委外加工单'),
    )

    id = models.AutoField(primary_key=True)
    admin_id = models.IntegerField(null=True, blank=True)
    goods_id = models.IntegerField(default=0)
    unit_price = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000, null=True, blank=True)
    tax_included = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000, null=True, blank=True)
    all_money = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000, null=True, blank=True)
    tax_money = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000, null=True, blank=True)
    money_tax_price = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000, null=True, blank=True)
    goods_unit = models.IntegerField(null=True, blank=True)
    stores_id = models.IntegerField(null=True, blank=True)
    batch_id = models.IntegerField(null=True, blank=True)
    number = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000, null=True, blank=True)
    purchase_code = models.CharField(max_length=50, null=True, blank=True)
    purchase_time = models.IntegerField(null=True, blank=True)
    business_type = models.CharField(max_length=2, choices=BUSINESS_TYPE_CHOICES, null=True, blank=True)
    customer_id = models.IntegerField(null=True, blank=True)
    sale_id = models.IntegerField(null=True, blank=True)
    remarks = models.CharField(max_length=255, null=True, blank=True)
    order_id = models.IntegerField(null=True, blank=True)
    createtime = models.IntegerField(null=True, blank=True)
    updatetime = models.IntegerField(null=True, blank=True)

    class Meta:
        db_table = 'fa_kuyou_goods_batch_log'
        verbose_name = '批次跟踪表'
        verbose_name_plural = verbose_name

    def __str__(self):
        return f"{self.purchase_code} (ID: {self.id})"


# 商品库存批次跟踪表
class FaKuyouGoodsBatchStock(models.Model):
    STATUS_CHOICES = (
        ('0', '关闭'),
        ('1', '正常'),
    )

    id = models.AutoField(primary_key=True)
    admin_id = models.IntegerField(null=True, blank=True)
    batch_id = models.IntegerField(null=True, blank=True)
    goods_id = models.IntegerField(default=0)
    goods_code = models.CharField(max_length=30, null=True, blank=True)
    attribute_id = models.IntegerField(default=0, null=True, blank=True)
    stores_id = models.IntegerField(default=0)
    stock = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000)
    status = models.CharField(max_length=1, choices=STATUS_CHOICES, default='1')
    createtime = models.IntegerField(null=True, blank=True)
    updatetime = models.IntegerField(null=True, blank=True)

    class Meta:
        db_table = 'fa_kuyou_goods_batch_stock'
        verbose_name = '商品批次库存表'
        verbose_name_plural = verbose_name

    def __str__(self):
        return f"{self.goods_code} (Batch: {self.batch_id}, Stock: {self.stock})"
